Skip to content
Advertisement

linux get specific fields from several files

I have several files starting with the string “file” then a number (file1, file2, etc).

The content of these files is similar and looks like this

file1:
$xx_ at 10.0 "$elt_(0) coordinates 636.46 1800.37 9.90"
$xx_ at 10.0 "$elt_(1) coordinates 367.78 1263.63 7.90"

For each file, I want only keep the index of the element and the 2 numeric fields just after coordinates (in the same file or in another file):

file1:

0  636.46 1800.37 
1 367.78 1263.63 

What I tried to do is like this (but It is not correct)

find . -name "file*"|while read fname; do
  echo "$fname"
  for line in $(cat "$fname") do
   FS="[_() ]"
   print   $7 "t" $10 "t" $11 > $fname
  done
done

Advertisement

Answer

This is the perfect use of awk. With awk you can simply print specific words.

If the index is the line number you can use this:

cat -n ./file1 | awk '{print $1 -1 " " $7 " " $8}' this simply prints the files with line numbers and prints the first, seventh and eighth word.

If the index is the $elt_(0) number in parenthese you can use sed like this:

cat ./file1 | awk '{print $4 " " $7 " " $8}' | sed 's/"$elt_(//g' | sed 's/)//g' | sed 's/"//g'

output:

1 636.46 1800.37
2 367.78 1263.63

Link to awk Link to sed

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement