Home > Software engineering >  Cannot print in awk command in bash script
Cannot print in awk command in bash script

Time:08-10

I am trying to read values from a file and print specific items into a variable which I will use later.

cat /dir1/file1 | while read blmbline2
do
    BLMBFILE2=`print $blmbline2 | awk '{$1=""; print $0}'`
    echo $BLMBFILE2
done

When I run that same code at the command line, it runs as expected, but, when I run it in a bash script called testme.sh, I get this error:

./testme.sh: line 3: print: command not found

If I run print by itself at the command prompt, I don't get an error (just a blank line).

If I run "bash" and then print at the command prompt, I get command not found.

I can't figure out what I'm doing wrong. Can someone suggest?

updated: I see some other posts that say to use echo or printf? Is there a difference I need to be concerned with in using one of those in bash?

CodePudding user response:

Since awk can read files, you may be able to do away with the cat | while read and just use awk. Using a sample file containing:

1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6

Declare your bash array variable and populate with the output from awk:

arr=() ; arr=($(awk '{$1=""; print $0}' /dir1/file1))

Use the following to display array size and contents:

printf "array length: %d\narray contents: %s\n" "${#arr[@]}" "${arr[*]}"

Output:

array length: 30
array contents: 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6 2 3 4 5 6

CodePudding user response:

Change print to echo in your shell script. With printf you can format the data and with echo it will print the entire line of the file. Also, create an array so you can store multiple items:

BLMBFILE2=()
while IFS=  read -r -d $'\0'
do
  BLMBFILE2 =(`echo $REPLY | awk '{$1=""; print $0}'`)
  echo $BLMBFILE2
done < <(cat /dir1/file1)

echo "Items found:"
for value in "${BLMBFILE2[@]}"
do
 echo $value
done
  • Related