4

I know this is a FAQ but I've already read multiple pages about this and I can't get it to work. I'm using the grep command to locate a range of values from three different text files.

Command line:

grep -o "201[1-4].[0-9][ -9]" file1.txt file2.txt file3.txt

Output:

file1.txt:2012.69
file1.txt:2013.44
file2.txt:2013.17
file2.txt:2012.6    
file2.txt:2013.75
file2.txt:2013.08
file3.txt:2013.54
file3.txt:2013.9    

I want the output to have the names of the three files as the first row (header) and then all of the values found to be in each column. I think the problem is that I am unable to predict how many rows I would need.

2

You can use awk to join the output of grep to one row per file, then transpose with csvtool and optional column -nt to make the output nice (note, that -n is a Debian extension and might not be available for your platform).

grep -o "201[1-4].[0-9][ -9]" file1.txt file2.txt file3.txt \
| awk -F: '
  {
    if (!s[$1]){ s[$1]=$2 }
    else { s[$1]=s[$1]","$2 }
  }
  END {
    for (f in s){ print f","s[f] }
  }' \
| csvtool transpose -u " " - \
| column -nt

Output:

file1.txt  file3.txt  file2.txt
2012.69    2013.54    2013.17
2013.44    2013.9     2012.6
                      2013.75
                      2013.08

You might need to install csvtool.

| improve this answer | |
  • 1
    make it column -nt, then it shows as it should. – markgraf Oct 14 '19 at 13:50
  • thanks, updated. – pLumo Oct 14 '19 at 13:51
  • -n only works like that with BSD column, not with the version in util-linux :-(. The latter is what’s installed on Fedora & co. – Stephen Kitt Oct 14 '19 at 13:54
  • as the whole column thing is optional, I'll leave it with that note ;-) – pLumo Oct 14 '19 at 13:55
  • You could transpose with awk, too: stackoverflow.com/a/1729980 ---I was tinkering with datamash and that. – markgraf Oct 14 '19 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.