LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Bash script - use current variable value as number to print a line (https://www.linuxquestions.org/questions/linux-software-2/bash-script-use-current-variable-value-as-number-to-print-a-line-4175664673/)

undefineduser 11-21-2019 07:34 AM

Bash script - use current variable value as number to print a line
 
Hey,

I'm working on a copy script that will copy all files that diff says only appear in the original directory, to the backup directory.

Diff gives me this output, so I have to work a little with the string to get the right target path.
Quote:

Only in /usr/share/icons/Adwaita/16x16/apps: user-info1.png
Only in /usr/share/icons/Adwaita/48x48/apps: goa-panel-symbolic.symbolic1.png
Only in /usr/share/icons/Adwaita/48x48/apps: help-browser-symbolic.symbolic1.png
Only in /usr/share/icons/Adwaita/48x48/apps: web-browser1.png
My idea was to count the number of lines of the diff file and write it to a variable. Inside the loop I then write the correct path of the current line into a new variable (or array).
If I write awk 'NR==$i' my variable is empty, with 'NR=='$i'' i get an EOF.

Any tips of how I can improve/fix my script?

Code:
Quote:

> #!/usr/bin/env bash
> #set -x
>
> count=$(awk 'END{print NR}' diffoutput.txt)
>
> for((i="1";i<=$count;++i))
> do
>> filename=$(awk 'NR==$i' diffoutput.txt | awk '{print $NF}')
>> # ...
> done
> true

undefineduser 11-21-2019 07:48 AM

Edit: Fixed it
 
I fixed it by adding -v i=$i!
Code:

filename=$(awk -v i=$i 'NR==i' sample.txt | awk '{print $NF}')

Firerat 11-21-2019 10:20 AM

Code:

cp --no-clobber /path/to/original/* /path/to/new/

Firerat 11-21-2019 06:26 PM

wait, you only want the last field?

Code:

#!/bin/bash

echo awk
awk '{print $NF}' sample.txt
echo sed
sed -E 's/.+[[:blank:]]([[:graph:]]+)$/\1/' sample.txt
echo grep
grep -Eo [[:graph:]]+$ sample.txt
echo bash
while read ;do printf "%s\n" "${REPLY##* }";done <sample.txt
echo or as array
while read -a ARRAY;do printf "%s\n" "${ARRAY[(-1)]}";done <sample.txt

note, those include both 16x16 and 48x48

the grep is not so useful if you need to factor that in

Code:

echo awk
awk '/16x16/{print $NF}' sample.txt
echo sed
sed -En 's/.+16x16.+[[:blank:]]([[:graph:]]+)$/\1/p' sample.txt
echo bash
while read
do
  [[ $REPLY =~ 16x16 ]] || continue
  printf "%s\n" "${REPLY##*[[:blank:]]}"
done <sample.txt
echo as array
while read -a ARRAY
do
  [[ ${ARRAY[(-2)]} =~ 16x16 ]] || continue
  printf "%s\n" "${ARRAY[(-1)]}"
done <sample.txt

#



All times are GMT -5. The time now is 09:14 PM.