简体   繁体   中英

Reformat text in in a file linux via a bash script

I have a bunch of text files with XML like this:

<?xml version="1.0"?>\n<cdr core-uuid="dba286e1-8eb4-4792-9f3b-ff358c06bcad">\n  <channel_data>\n    <state>CS_REPORTING</state>\n    <direction>inbound</direction>\n    <state_number>11</state_number>\n

It is all on one line and I want to format each \\n (newline char) into an actual line break and save the file. How do I do this?

Try this.

sed -i.save -e 's/\\n/\n/g' <file>

It will edit the file in place, and save the original file with extension ".save".

The sed command can do exactly this:

sed 's/\\n/\n/g' input_file > output_file

This uses sed's substitution operator to replace all occurrences of "\\n" with a newline character. The substitution command follows the syntax

s/search_regex/replacement_text/operands

In this case, the search regex is '\\n', which searches for a literal backslash followed by 'n', and it is replaced by the newline character '\\n'. The operand 'g' causes this to run over the whole file, not just the first occurrence. Note also that the entire replacement string is quoted, so that bash doesn't do a level of escaping before passing to sed.

Try man sed or look here for more information: http://www.grymoire.com/Unix/Sed.html

There is the quick and dirty regex method:

perl -pe 's!\n!<br/>!sg' 

Not sure if it is sufficient for your needs though.

Pure Bash:

while read -r line ; do
  echo -e "$line"
done < "$infile" > "$outfile"

The quotes in the echo statement preserve all whitespaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM