I want to add hashes to all the lines in a regular text file. I'm fine with both the use of terminal and GUI—I just need to get it done.
8 Answers
You can use sed to do that:
sed -i.bak 's/^/##/' file
This replaces the start of the line (^) with ##.
With the -i.bak switch, sed edits the file in-place, but creates a backup copy with extension.bak.
- 37,734
- 1,021
Here is a solution to this problem using perl
perl -e 'while (<>) {print "##$_"}' < infile > outfile
- 374
While we are at it:
gawk -i inplace '{print "##"$0}' infile
This uses the (comparatively new) inplace editing plugin for GNU awk 4.1.0+.
Here's a bash way:
while read -r; do printf '##%s\n' "$REPLY"; done < infile > outfile
(In the bash shell, running read -r with no other arguments works like IFS= read -r REPLY.)
This is stylistically inspired by beav_35's perl solution, which I admit probably runs much faster for huge files, since perl may be expected to be more efficient than a shell when it comes to text processing.
- 119,640
sed -i is not POSIX-standard, so if you are a purist you will want to use ed:
printf ",s/^/##/\nw\nq" | ed -s file.txt
- 12,813
Here's an easier perl way than presented elsewhere:
perl -pi -e 'print "##"' YOURFILEHERE
This (ab)uses the fact that perl -p prints the line after executing the command given in -e.
- 375
- 1
- 2
- 11
You can use Vim in Ex mode:
ex -sc '%s/^/##/|x' file
%select all linesssubstitutexsave and close
- 1
Can be done with python's mapping function and redirecting stdin:
$ cat input.txt
lorem ipsum
quick brown fox
hello world
$ python -c 'import sys;print "".join(map(lambda x: "##"+x,sys.stdin.readlines()))' < input.txt
##lorem ipsum
##quick brown fox
##hello world
Save the output to new file and use it instead of original
- 107,582