0

I have a loop that processes a bunch of files within a dir. I would like to input the filename into the file it processes, but I'm getting an error. It works perfectly with the myvar syntax but I need that for obvious reasons.

Error

awk: cmd. line:1: RS=
awk: cmd. line:1:    ^ unexpected newline or end of string

Command

for filename in $files
do
    awk -v "myvar=${filename}" 
      RS= '/-- Ticket/{++i; print "PROMPT myvar Line ", 
      i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
done
1
  • awk -v myvar="$filename" -v RS= '/-- Ticket/{++i; print "PROMPT", myvar, "Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' "$filename.txt" Commented Mar 29, 2017 at 18:12

2 Answers 2

1

Couple of issues here, use the -v syntax for each of the variables that you are trying to pass to awk,

awk -v myvar="${filename}" -v RS= '/-- Ticket/{++i; print "PROMPT " myvar " Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
#  ^^^ variable1           ^^^^^ variable2 --> using separate -v for each

should be right approach.

For a shell variable import to awk do it as in my example above, not as "myvar=${filename}" but just myvar="${filename}"

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

4 Comments

Yeah I did try this approach and the error I got is: awk: cmd. line:1: RS= awk: cmd. line:1: ^ unexpected newline or end of string
@luckytaxi: try it exactly as in my answer.
Right, ok so i had to put PROMPT myvar Line but it's not printing myvar
@luckytaxi: Refer my update, try awk -v myvar="${filename}" -v RS= '/-- Ticket/{++i; print "PROMPT "myvar" Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
0

If you could avoid a batch loop, it's better (performance mainly for subshell fork, ...)

# assume TXT_files is the list of $files with .txt extension (not purpose of this OP)
awk RS='' '
   /-- Ticket/{
     # get the file name without extension
     myvar = FILENAME;sub( /\.txt$/,"",myvar)

     print "PROMPT " myvar " Line " ++i ORS $0 ORS

     i += split( $0, a, /\n/) + 1
     }
   ' ${TXT_files}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.