0

Trying to pass a bash variable to an awk script to insert a value in front of each line, currently the script runs but prints 0 in each line. Thank you :).

file

2022/.../.../...
2022/.../.../...

awk

id=1234

awk -v r="$id" '{print /"id"/"/"$0}'   

current

0/2022/.../.../...
0/2022/.../.../...

desired

1234/2022/.../.../...
1234/2022/.../.../...
1
  • 2
    Use: awk -v r="$id" '{print r "/" $0}' Commented Aug 30, 2022 at 14:37

2 Answers 2

1

You are passing variable correctly but not using correctly inside the awk. /"id"/" is a regex expression that will attempt to match "id" string in each line and since it doesn't exist it returns 0 and that's what you get in output.

You may just use:

awk -v r="$id" '{print r "/" $0}' file

1234/2022/.../.../...
1234/2022/.../.../...

btw this sed solution would also work:

sed "s~^~$id/~" file

1234/2022/.../.../...
1234/2022/.../.../...
Sign up to request clarification or add additional context in comments.

Comments

1

this should make it clear why it appended "0/" :

0/
    # gawk profile, created Tue Aug 30 14:49:38 2022

    # Rule(s)

     1  {
     1      print (/"id"/) "/" $0
    }

It's a regex non-match, concat with a string containing ASCII "/" (\057 | 0x2F)`, then concat with input row

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.