Bash - how to put each line within quotation

后端 未结 7 1285
既然无缘
既然无缘 2020-12-30 21:14

I want to put each line within quotation marks, such as:

abcdefg
hijklmn
opqrst

convert to:

\"abcdefg\"
\"hijklmn\"
\"opqrs         


        
相关标签:
7条回答
  • 2020-12-30 21:34

    Use sed:

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

    More effort needed if the file contains empty lines.

    0 讨论(0)
  • 2020-12-30 21:36

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

    0 讨论(0)
  • 2020-12-30 21:44

    I think the sed and awk are the best solution but if you want to use just shell here is 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
    
    0 讨论(0)
  • 2020-12-30 21:46

    This sed should work for ignoring empty lines as well:

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

    or

    sed 's/^.\{1,\}$/"&"/' inFile
    
    0 讨论(0)
  • 2020-12-30 21:48

    I use the following command:

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

    The xargs take standard input (redirected from your file) and pass one line a time to {lin} placeholder, and then execute the command at next, in this case a echo with escaped double quotes.

    You can use the -i option of xargs to omit the name of the placeholder, like this:

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

    In both cases, your IFS must be at default value or with '\n' at least.

    0 讨论(0)
  • 2020-12-30 21:53

    I used sed with two expressions to replace start and end of line, since in my particular use case I wanted to place HTML tags around only lines that contained particular words.

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

    Similar to:

    $ bla=foo
    $ sed -e "/${bla}/s#^#<P>#" -e "/${bla}/s#\$#</P>#" inputfile
    <P>foo</P>
    bar
    $
    
    0 讨论(0)
提交回复
热议问题