Issue
Any chance someone knows a way ( working on RHEL7 and AIX5 ) to make a script that runs either on /bin/bash or /bin/ksh to search in a text file for 1 or more strings using grep ( or another function ), the results being put in a variable but in that variable to have a string "\\n" placed at the end of each occurance?
For example:
TextFile1.txt
[root@server ~]$ cat TextFile1.txt
aby ORA-3120: unable to xx
sxyy unable to aa
sxyy ORA-3120: unable to aa
ytxy unable to bb
y41y unable to dd
yanby unable to ff
ytxy ORA-3120: unable to bb
y41y ORA-3120: unable to dd
y124gby unable to gg
yanby ORA-3120: unable to ff
aby unable to xx
y124gby ORA-3120: unable to gg
Simple Grep
[root@server ~]$ cat TextFile1.txt | grep "ORA-"
aby ORA-3120: unable to xx
sxyy ORA-3120: unable to aa
ytxy ORA-3120: unable to bb
y41y ORA-3120: unable to dd
yanby ORA-3120: unable to ff
y124gby ORA-3120: unable to gg
Put the results in a variable
[root@server ~]$ aa=$(cat TextFile1.txt | grep "ORA-")
[root@server ~]$ echo $aa
aby ORA-3120: unable to xx sxyy ORA-3120: unable to aa ytxy ORA-3120: unable to bb y41y ORA-3120: unable to dd yanby ORA-3120: unable to ff y124gby ORA-3120: unable to gg
Desired result:
[root@server ~]$ echo $aa
\\n aby ORA-3120: unable to xx \\n sxyy ORA-3120: unable to aa \\n ytxy ORA-3120: unable to bb \\n y41y ORA-3120: unable to dd \\n yanby ORA-3120: unable to ff \\n y124gby ORA-3120: unable to gg \\n
Thank you in advance for the help and hints
Solution
There are many ways to do this. Here are two:
Piping grep
's output to sed
:
aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | sed 's/\(.*\)/\1 \\\\n/')
Output:
$ aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | sed 's/\(.*\)/\1 \\\\n/')
$ echo $aa
\\n aby ORA-3120: unable to xx \\n sxyy ORA-3120: unable to aa \\n ytxy ORA-3120: unable to bb \\n y41y ORA-3120: unable to dd \\n yanby ORA-3120: unable to ff \\n y124gby ORA-3120: unable to gg \\n
$
Piping grep
's output to awk:
aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | awk '{print $0 " \\\\n"}')
Output:
$ aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | awk '{print $0 " \\\\n"}')
$ echo $aa
\\n aby ORA-3120: unable to xx \\n sxyy ORA-3120: unable to aa \\n ytxy ORA-3120: unable to bb \\n y41y ORA-3120: unable to dd \\n yanby ORA-3120: unable to ff \\n y124gby ORA-3120: unable to gg \\n
Answered By - Luis Guzman