Extracting part of lines with specific pattern using awk or sed
Solution 1
With grep
:
grep -oP 'sum=\K.*' inpufile > outputfile
grep with -P
(perl-regexp) parameter supports \K
, which use to ignoring the previously matched characters.
With awk
:
awk -F"=" '{ print $NF; }' inputfile > outputfile
in awk the variable NF
represent the total number of fields in a current record/line which is point to the last field number too and so $NF
is its value accordingly.
With sed
:
sed 's/^.*sum=//' inpufile > outputfile
^.*=sum
replace all characters(.*
) between starting of line(^
) and last characters(sum=
) with whitespace char.
Result:
-6.97168e-09
6.97168e-09
-5.12623e-12
5.12623e-12
-6.936e-09
6.97169e-09
-5.1e-12
5.12624e-12
With cut
:
cut -d'=' -f2 inputfile > outputfile
if you want save same values into a same file and each separately, with awk
you can do:
awk -F"=" '{print $NF >($NF); }' inputfile > outputfile
Solution 2
If I correctly understand the question you want to get only values after =
, and store the these values in separate files, based on second field(?). If I'm right try something like this:
$ awk -F'[ =]' '{print $6>"file_"$2".txt"}' file
The result:
$ ls -1
file_leftWallPhi.txt
file_leftWallUSf.txt
file_leftWallrhoPhi.txt
file_leftWallrhoUSf.txt
file_loweWallrhoPhi.txt
file_loweWallrhoUSf.txt
file_lowerWallPhi.txt
file_lowerWallUSf.txt
$ cat file_leftWallPhi.txt
5.12623e-12
Solution 3
You can do it by sed
sed -E 's/^.* (\S+)\s*:.*=(\S+)/echo "\2" > "\1".txt/' file | bash
The script find out two pieces in line:
- between spaces and
:
and should contain some(more then 0) non-space symbols ; - some(more then 0) non-space symbols after
=
;
and format from its in execution command which transfered through the pipe to bash
John Johnny
Updated on September 18, 2022Comments
-
John Johnny over 1 year
I have a problem with following algorithm, What should be done to resolve this problem I type a year if the year is not a leap year I will need to type again untill the typed year is a leap year.
int year = 0; BOOL yearC; NSLog(@"Enter the year to be tested;"); scanf ("%i", &year); yearC = ((year % 4 == 0 && year % 100 !=0)|| year % 400 == 0); if ( yearC ) NSLog (@"It's a leap year."); else { NSLog (@"Nope, it's not a leap year."); scanf ("%i", &year); } }
-
gasparuff almost 11 yearsHave you considered using a
while
-loop? -
Daij-Djan almost 11 yearsuse a while loop to solve the assignment
-
Git.Coach almost 11 yearsI would use a loop for this. In this case "while" should do the trick. ;-) Never give up, keep on improving! :)
-
Desdenova almost 11 years
-
-
Git.Coach almost 11 yearsAaaaand: Homework's done.
-
jimmij over 9 years@KasiyA I cannot reproduce your problem with GNU awk 4.0.2. The command from my answer works also with
-c
option (compatibility mode with traditional UNIXawk
where GNU extensions are disabled). Please be sure you have updated input file as the original question was edited and empty lines deleted.