1

In linux, how to create a file with content whose single line with \n (or any line separator) is translated into multi-line.

fileA.txt:
trans_fileA::abcd\ndfghc\n091873\nhhjj 
trans_fileB::a11d\n11hc\n73345

Code:

while read line; do
         file_name=`echo $line | awk -F'::' '{print $1}' `
         file_content=`echo $line | awk -F'::' '{print $2}' `
             echo $file_name
             echo $(eval echo ${file_content}) 
         echo $(eval echo ${file_content}) > fileA.txt

The trans_fileA should be:

abcd
dfghc
091873
hhjj

Please suggest

2

Using the bash shell:

while IFS= read -r line; do
    name=${line%%::*}
    contents=${line#*::}

    echo -e "$contents" >"$name"
done <fileA.txt

This reads the input file line by line and extracts the output filename and the contents form the read line using standard parameter substitutions. ${variable%%pattern} removes the longest matching substring from the tail end of $variable that matches pattern, while ${variable#pattern} removes the shortest matching substring from the start of $variable that matches pattern.

The value of line is read with read -r so that the backslashes are preserved in the data. Without -r, read would not preserve these. We also set IFS to an empty string before calling read so that no flanking whitespace is trimmed from the data.

The output is done using echo -e, which interprets the escape sequences in the data. This means that it will replace the \n in the data with actual newlines.

After running this, you will have

$ ls -l
total 12
-rw-r--r--  1 kk  wheel  71 Jun 17 16:28 fileA.txt
-rw-r--r--  1 kk  wheel  24 Jun 17 16:31 trans_fileA
-rw-r--r--  1 kk  wheel  16 Jun 17 16:31 trans_fileB
$ cat trans_fileA
abcd
dfghc
091873
hhjj
$ cat trans_fileB
a11d
11hc
73345

Related:

0

My first thought was sed Given your file, fileA.txt above:

abcd\ndfghc\n091873\nhhjj

and running sed against newline.sed which contains:

s/\\n/\
/g

thusly

sed -f ./newline.sed <./fileA.txt >./trans_fileA

will return these results in trans_fileA:

abcd
dfghc
091873
hhjj

This was the simplest way I could figure to accomplish your task.

HTH

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.