0

I have a file called phone_dir.txt (2 lines for example):

ADAMS, Andrew 7583
BARRETT, Bruce 6466

I try to extract the last names and capitalize them, the output required is:

Adams
Barret

I can only use commands such as:

  • cut
  • paste
  • tr

I tried running the following script but the results are inconsistent:

cut -c1 phone_dir.txt > last_names.txt | cut -f1 -d',' phone_dir.txt | cut -c2- | tr A-Z a-z | paste last_names.txt - | tr -d [:blank:]

Sometimes the output is:

Adams
Barret

And sometimes

dams
arret

Why are the results inconsistent?

2
  • 3
    awk or perl are more suited for this job... Is this homework ? Dec 6, 2016 at 18:33
  • You're sending the output of cut into last_names.txt but also trying to pipe it ? Unlikely you truly want to attempt both actions.
    – steve
    Dec 6, 2016 at 18:51

1 Answer 1

1

If you're allowed to create a temporary file, how about this?

in=phone_dir.txt
out=last_names.txt
tmp=$$tmp && \
a=$(cut -d',' -f1 "$in" | tee >(cut -c2- | tr [:upper:] [:lower:] > "$tmp") | cut -c1) && \
paste  <(printf "%s\n" ${a[@]}) "$tmp" | tr -d [:blank:] > "$out" && \
rm "$tmp"
2
  • 1
    You inspired me by using '<()' to write this solution with no temp files: cut -f1 -d',' phone_dir.txt | cut -c2- | tr A-Z a-z | paste <(cut -c1 phone_dir.txt) - | tr -d [:blank:] > last_names.txt Dec 6, 2016 at 20:52
  • @DorShmaryahu Well done. Simpler and faster.
    – user147505
    Dec 7, 2016 at 0:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .