Home > Mobile >  Linux cut and add the output at the beginning of the same file
Linux cut and add the output at the beginning of the same file

Time:10-11

For example, I have a file with name file1 and the contents are as below

var/lib/repos/main1:v1 2gb
var/lib/repos/main2:v2 1gb
…

So I want the output to be as follows

main1 var/lib/repos/main1:v1 2gb
main2 var/lib/repos/main2:v2 1gb

I tried the following command:

cut -d’/‘ -f 4 | cut -d”:” -f1 file1

CodePudding user response:

You may consider this sed solution:

sed -E 's~.*/([^:] ):.*~\1 &~' file

main1 var/lib/repos/main1:v1 2gb
main2 var/lib/repos/main2:v2 1gb

Breakup:

  • .*: Match 0 or more of any char (longest match due to greediness)
  • /: Match a /
  • ([^:] ): Match 1 of any char that is not / and capture in group #1
  • :: Match a :
  • .*: Match 0 or more of any char (longest match due to greediness)
  • \1 &: Place first group's capture value and space in front of matched line

Or else this awk command would also work:

awk -F: 'n=split($1, a, /\//) {print a[n], $0}' file

main1 var/lib/repos/main1:v1 2gb
main2 var/lib/repos/main2:v2 1gb

CodePudding user response:

Using awk:

awk 'match($0, /main[0-9]/) { print substr( $0, RSTART, RLENGTH ) " " $0}' file1

main1 var/lib/repos/main1:v1 2gb
main2 var/lib/repos/main2:v2 1gb
  • Related