sed - grep part of nth lines linux -
i have file like:
something1 something2 201101130000 thing thing1 thing2 aaa, -2, 4, 0, 54; thing3 thing4 aaa, 43, 43, 0, 5, 0, 0,; thing5 aaa, 132.0, 43.0, 0.0, 0.0, 43.0,210.0,' thing5
how re-create date (201101130000) sec line, add together comma (,) set numbers of line before lastly (132,0, 43.0, 0.0, 43.0, 210.0) in newfile.txt new file should like:(the original file not have spaces between lines here)
20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0
i tried grep , sed no luck. help
here's how i've interpreted question:
you're trying 'grep' , bring together parts of 2 lines. these 2 lines sec , sec lastly lines.
you're trying redirect output file. can utilize shell redirection this, like: awk ... file > outputfile
.
here's 1 way using sed
:
sed '2h; $!n; $!d; ${ g; s/[^,]*\([^\n]*\).* \([0-9]\{8\}\).*/\2\1/; s/..$// }' file
since you've tagged linux, i'm guessing you've got gnu sed
, don't mind golf:
sed -r '2h;$!n;$!d;${g;s/[^,]*([^\n]*).*\s([0-9]{8}).*/\2\1/;s/..$//}' file
results:
20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0
explanation:
2h # re-create sec line hold space $!n # if not lastly line append next line $!d # if not lastly line delete first newline in pattern $ { ... } # 1 lastly line, perform 2 substitutions
alternatively, awk
may easier understand:
awk 'fnr==nr { c++; next } fnr==2 { x = substr($nf,0,8) } fnr==c-1 { sub(/[^,]*/,x); sub(/..$/,""); print }' file file
results:
20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0
explanation:
fnr==nr { c++; next } # read first file in arguments list, # count of number of lines in file fnr==2 { ... } # when reading sec line of sec file in # arguments list, take substring of lastly field fnr==c-1 { ... } # 1 sec lastly line of sec file in # arguments list, perform 2 substitutions , print # line.
linux sed grep
No comments:
Post a Comment