Bash - how to put each line in a quote

I want to put each line in quotation marks, for example:

abcdefg hijklmn opqrst 

convert to:

 "abcdefg" "hijklmn" "opqrst" 

How to do this in a bash shell script?

+6
source share
7 answers

Using awk

 awk '{ print "\""$0"\""}' inputfile 

Using pure bash

 while read FOO; do echo -e "\"$FOO\"" done < inputfile 

where inputfile will be a file containing strings without quotes.

If your file has empty lines, awk is definitely a way:

 awk 'NF { print "\""$0"\""}' inputfile 

NF tells awk to only execute a print command when the number of fields is greater than zero (the line is not empty).

+17
source

I use the following command:

 xargs -I{lin} echo \"{lin}\" < your_filename 

xargs accepts standard input (redirected from your file) and passes one line of time to the {lin} placeholder, and then runs the following command, in this case a echo with escaped double quotes.

You can use the -i option for xargs to omit the placeholder name, for example:

 xargs -i echo \"{}\" < your_filename 

In both cases, your IFS should be the default or '\n' at least.

+5
source

Use sed:

 sed -e 's/^\|$/"/g' file 

More effort is required if the file contains empty lines.

+4
source

I think sed and awk are the best solution, but if you want to use only the shell, this is a 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 
+3
source

This sed should also work to ignore empty lines:

 sed -i.bak 's/^..*$/"&"/' inFile 

or

 sed 's/^.\{1,\}$/"&"/' inFile 
+3
source
 paste -d\" /dev/null your-file /dev/null 

(not the most beautiful, but probably the fastest)

Now, if the input may contain quotes, you may need to escape them with backslashes (and then escape backslashes), for example:

 sed 's/["\]/\\&/g; s/.*/"&"/' your-file 
0
source

I used sed with two expressions to replace the beginning and end of a line, since in my particular use case I wanted to place HTML tags only on lines containing specific words.

So, I searched for lines containing the words contained in the bla variable in the inputfile text file, and replaced beginnign with <P> and the end with </P> (well, actually, I made some longer HTML tags in the real thing but this will serve as an example perfectly)

Similarly:

 $ bla=foo $ sed -e "/${bla}/s#^#<P>#" -e "/${bla}/s#\$#</P>#" inputfile <P>foo</P> bar $ 
0
source

Source: https://habr.com/ru/post/946810/


All Articles