1

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
MevlütÖzdemir
  • 3,180
  • 1
  • 23
  • 28

7 Answers7

10
sed 's/.*/"&",/' file

In the replacement part of a substitution, & is replaced with whatever matched the original regular expression. .* matches the whole line.

Barmar
  • 741,623
  • 53
  • 500
  • 612
3

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 on
  • s/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 comma
Aaron
  • 24,009
  • 2
  • 33
  • 57
2

sed (the Stream EDitor) is one choice for this manipulation:

sed -e 's/^/"/;s/$/",/' file

There are two parts to the regular expression, separated by ;:

  1. s/^/"/ means add a " to the beginning of each line.
  2. 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.

bishop
  • 37,830
  • 11
  • 104
  • 139
2

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).

Community
  • 1
  • 1
Srini V
  • 11,045
  • 14
  • 66
  • 89
1

Just to be different: perl

perl -lne 'print qq{"$_",}' file
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

This is a simple one liner:

sed -i 's/^/"/;s/$/",/' file_name
Patrick Trentin
  • 7,126
  • 3
  • 23
  • 40
0
> echo $word
word
> echo "\""$word"\","
"word",

See How to escape double quotes in bash?

Community
  • 1
  • 1
Dan Cornilescu
  • 39,470
  • 12
  • 57
  • 97