Home > Net >  Simplest way to replace (\n) with (" ") in bash?
Simplest way to replace (\n) with (" ") in bash?

Time:09-21

In a plain text file, I am trying to get from

 Item 1
 Item 2

to

 "Item 1" "Item 2"

I tried using the tr command (cat FILE.txt | tr "\n" "\" \""), but that did not work.
I also tried using cat FILE.txt | tr '\n' '\" \"', but again, no avail.

Can anyone help me do it?


Also, as a bonus question, what is the easiest way to get the first double quote?
With my method, if I get it to work, I will end up with:

Item 1" "Item 2"

P.S. Thanks Jorengarenar for helping me with the edit.

CodePudding user response:

One possibility would be to use awk.

awk '{ printf " " "\""$0"\"" }' FILE

For the bonus question, just remove the second quote after the $0 variable.

awk '{ printf " " "\""$0"" }' FILE

If you want another delimiter, you can change the first argument to whatever you like.

CodePudding user response:

Try this:

awk '{printf spacer "\"" $0 "\""; spacer=" "} END {print ""}' FILE.txt

Explanation: for each line, this prints a spacer (which is initially empty), a literal double-quote, the original line (not including its terminating newline), and another literal double-quote. Then, it sets spacer to a single space, so that for all but the first line there'll be a space printed before it. printf doesn't add a newline, so all of this gets printed as a single long line. But at the end, we need to add a final newline, which a normal print takes care of.

CodePudding user response:

If you want to change the file itself, one way using ed:

ed -s file.txt <<'EOF'
1,$ s/^/"/
1,$ s/$/" /
1,$ j
w
EOF

First add a double quote to the beginning of every line, then a double quote and space to the end, and finally join all the lines into one and write the changed file back to disk.

CodePudding user response:

In two steps: 1.cat FILE.txt | tr '\n' ' ' 2.sed -E 's:([a-zA-Z0-9] ):"\1":g' FILE.txt

  • Related