I have a file (test.txt), where the separator is ;. How can I write out the last element from each row? (the length of each element is different)

sed 's/.*;//' < test.txt

Deletes everything up to the last ; on each line.

Or with awk:

awk -F';' '{print $NF}' < test.txt

If you know in advance the number of fields, you can use cut. For instance, if there are 4 fields:

cut -d';' -f4 < test.txt

Beware though that if there are fewer than 4 fields on a line, then it will return an empty line except if there's only one field (no ; in the line), in which case it will output the full line (that first field). A known misfeature in cut.

while read line;
 echo $(echo $line | awk -F ';' '{print $NF}')
done < test.txt

This is a simple script this will take each line of test.txt as input and will the print the last element separated by ;.


Or in bash:


while read line ; do
    echo ${a##*;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.