Manoj.V
Manoj.V

Reputation: 37

How to take the first field of each line from a text file and execute it in a while-loop?

I tried with below script. But, not working for cut the first field of each line and to be executed for "chmod".

#!/bin/bash
if [ -z "$1" ]; then
    echo -e "Usage: $(basename $0) FILE\n"
    exit 1
fi

if [ ! -e "$1" ]; then
     echo -e "$1: File doesn't exist.\n"
     exit 1
fi

while read -r line; do
   awk '{print $1}'
   [ -n "$line" ] && chown root "$line" && echo -e "$line Ownership changed"
done < "$1"

Upvotes: 0

Views: 1837

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52172

You could extract the first word on each line with awk and pipe to xargs, invoking chown only as few times as possible:

awk '{print $1}' "$1" | xargs chown root

Upvotes: 1

Lety
Lety

Reputation: 2603

If field separator is space, try this:

while read -r line; do
   FILE_TO_CHANGE=$(echo $line | awk '{print $1}')
   [ -n "$line" ] && chown root "$FILE_TO_CHANGE" && echo -e "$line Ownership changed"
done < "$1"

awk read $line and print first token on standard output, the result is saved in FILE_TO_CHANGE variable and then it is used to run chown.

Another way could be:

awk '{print $1}' $1 | while read line; do
   chown root "$line" && echo -e "$line Ownership changed"
done

awk read your file and print the first field of each line, in this case, while loop read awk output line by line and run chown on field.

Upvotes: 2

Related Questions