I want to put each line within quotation marks, such as:
abcdefg
hijklmn
opqrst
convert to:
\"abcdefg\"
\"hijklmn\"
\"opqrs
Use sed:
sed -e 's/^\|$/"/g' file
More effort needed if the file contains empty lines.
Using awk
awk '{ print "\""$0"\""}' inputfile
Using pure bash
while read FOO; do
echo -e "\"$FOO\""
done < inputfile
where inputfile
would be a file containing the lines without quotes.
If your file has empty lines, awk is definitely the way to go:
awk 'NF { print "\""$0"\""}' inputfile
NF
tells awk
to only execute the print command when the Number of Fields is more than zero (line is not empty).
I think the sed and awk are the best solution but if you want to use just shell here is small script for you.
#!/bin/bash
chr="\""
file="file.txt"
cp $file $file."_backup"
while read -r line
do
echo "${chr}$line${chr}"
done <$file > newfile
mv newfile $file
This sed should work for ignoring empty lines as well:
sed -i.bak 's/^..*$/"&"/' inFile
or
sed 's/^.\{1,\}$/"&"/' inFile
I use the following command:
xargs -I{lin} echo \"{lin}\" < your_filename
The xargs
take standard input (redirected from your file) and pass one line a time to {lin}
placeholder, and then execute the command at next, in this case a echo
with escaped double quotes.
You can use the -i
option of xargs to omit the name of the placeholder, like this:
xargs -i echo \"{}\" < your_filename
In both cases, your IFS must be at default value or with '\n'
at least.
I used sed with two expressions to replace start and end of line, since in my particular use case I wanted to place HTML tags around only lines that contained particular words.
So I searched for the lines containing words contained in the bla
variable within the text file inputfile
and replaced the beginnign with <P>
and the end with </P>
(well actually I did some longer HTML tagging in the real thing, but this will serve fine as example)
Similar to:
$ bla=foo
$ sed -e "/${bla}/s#^#<P>#" -e "/${bla}/s#\$#</P>#" inputfile
<P>foo</P>
bar
$