0

So i am wring a script that would take several files, compare them and then output the different records.

The script is working fine for 3 parameter ( 3 files ), but i am having trouble to make the parameters vary.

Consider the script is named Test.

If i write: Test 1.txt 2.txt, The script will know that i have 2 inputs, which are 2 files and will compare them and give me an output.

Furthermore, if i write Test 1.txt 2.txt 3.txt, The script will know that i have 3 inputs, which are 3 files, compare them and give me an output.

The script now has the following commands :

awk 'NR>2' ${1} | awk '{print $NF "\r"}' > N1
awk 'NR>2' ${2} | awk '{print $NF "\r"}' > N2
awk 'NR>2' ${3} | awk '{print $NF "\r"}' > N3

This is working fine for 3 files, but the problem is that sometimes i have 2 files, sometimes i have 4 files.

I know i can fix that using loops, but i am new to this language and not very familiar with the syntax.

Thank you for your help :)

0

2 Answers 2

2

use this :

x=1
for i in "$@"
do
  awk 'NR>2' $i | awk '{print $NF "\r"}' > N$x
  x=$(($x+1))
done

$@ : list of input parameters

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

3 Comments

Nice short answer! Please note that incrementing x can also be written ((x++)), a shorter syntax which is easier to remember for all programmers :)
This is wrong, but easy to fix. You specifically must use double quotes around $@ in order for quoted arguments to work properly.
@Necro1992 Take tripleee's advice and quote "$@" -- it will break the first time you use a filename with a space.
1

Your awk commands can be combined: awk 'NR>2 {print $NF "\r"}' "$1" > N1.

Better yet, a single awk command to process all files:

awk '
    FNR == 1 {output = "N" ++count}
    FNR > 2  {print $NF "\r" > output}
' "$@"

"One awk to rule them all"

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.