Home > Back-end >  Print specific lines using sed from a grep output
Print specific lines using sed from a grep output

Time:01-24

I'm practicing following tutorials, my goal is searching only on users, and printing into a txt file, so I have the next command so far.

cat /etc/passwd | awk -F ":" '{print $1}' | grep -n $search_param

Here I get an output of all the lines that match the criteria of $search_param. But now I wanna use sed to display it, so I can replace the ":" delimiters with for example "\t" in sed exp. After that I just make a file, but my trouble is filtering only using the first column with grep, and proceed to show all the information it has on that desired line.

I tried piping it directly into sed but it doesn't seem to work as it will technically seed the line numbers, not the specific lines on /etc/passwd.

CodePudding user response:

cat-to-awk-to-grep-to-sed is a painful antipattern. Just use awk.

awk -F: -v key="$search_param" '$1~key { print $1 "\t" $5 }' /etc/passwd

You could also space-pad, truncate, and even right-align. printf is pretty flexible.

awk -F: -v key="$search_param" '$1~key{printf "% 20.20s\t% 40.40s\n", $1, $5}' /etc/passwd
  • Related