I have a file with one word on each line, I want to add a "
before the word, and a ",
after the word with Bash.
Example:
Hello
Sleep
Try
And I want:
"Hello",
"Sleep",
"try",
Hope anyone can help me
I have a file with one word on each line, I want to add a "
before the word, and a ",
after the word with Bash.
Example:
Hello
Sleep
Try
And I want:
"Hello",
"Sleep",
"try",
Hope anyone can help me
sed 's/.*/"&",/' file
In the replacement part of a substitution, &
is replaced with whatever matched the original regular expression. .*
matches the whole line.
Assuming you've got one word per line, I'd use the following GNU sed command :
sed -i 's/.*/"\0",/' <your_file>
Where you replace <your_file>
by the path to your file.
Explanation :
sed
means Stream EDitor ; it specialise in filtering and transforming text streams-i
is it's in-place option : it means it will write the result of its transformation in the file it's working ons/search/replace/
is sed
's search & replace command : it search for a pattern written as regular expression, and replace the matched text by something else.*
is a regex pattern that will match as much as it can. Since sed
works line by line, it will match a whole line\0
is a back-reference to the whole matched string"\0",
is the whole matched string, enclosed in quotes, followed by a comma.s/.*/"\0",/
is a sed
search&replace command that will match a whole line and enclose it in quotes, following it by a commased
(the Stream EDitor) is one choice for this manipulation:
sed -e 's/^/"/;s/$/",/' file
There are two parts to the regular expression, separated by ;
:
s/^/"/
means add a "
to the beginning of each line.s/$/",/
means add a ",
to the end of each line.The magic being the anchors for start of line (^
) and end of line ($
). The man page has more details. It's worth learning sed.
Already answered here
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).