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
  • 669,327
  • 51
  • 454
  • 560
MevlütÖzdemir
  • 2,741
  • 1
  • 21
  • 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
  • 669,327
  • 51
  • 454
  • 560
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
  • 23,167
  • 2
  • 30
  • 53
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
  • 34,858
  • 10
  • 96
  • 130
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
SriniV
  • 10,691
  • 14
  • 59
  • 88
1

Just to be different: perl

perl -lne 'print qq{"$_",}' file
glenn jackman
  • 223,850
  • 36
  • 205
  • 328
0

This is a simple one liner:

sed -i 's/^/"/;s/$/",/' file_name
Patrick Trentin
  • 6,976
  • 3
  • 24
  • 39
0
> echo $word
word
> echo "\""$word"\","
"word",

See How to escape double quotes in bash?

Community
  • 1
  • 1
Dan Cornilescu
  • 38,757
  • 12
  • 59
  • 95