1

I'm trying to execute a sed command with "-n" option.

for i in 1 2 3 4 5 ; do maas maas nodes list | grep hostname | cut -d\" -f4 | sed -n '$ip'; done

I want it to run sed -n '1p' then sed -n '2p' and so on.

Any idea?

Oli
  • 293,335

1 Answers1

2

You want to replace $i in $ip with your shell variable? Use double-quotes

... | sed "$ip" ...

This has certain implications. It doesn't apply here but you might have to escape things you wouldn't need to in single-quote-marks.

But I'd also consider rewriting that so you're not running the same commands n times to print the first n lines (which is what this does). Here are some alternatives...

Using head:

maas maas nodes list | grep hostname | cut -d\" -f4 | head -5

Storing the command output:

output=$(maas maas nodes list | grep hostname | cut -d\" -f4)
for i in 1 2 3 4 5; do
    sed -n "$ip"
done

Creating a better sed string:

maas maas nodes list | grep hostname | cut -d\" -f4 | sed -n $(printf "%dp;" {1..5})

Roll all your search/trim code into one awk:

maas maas nodes list | awk -F'"' '/hostname/ && i<5 {i++; print $4}'

I'm an awk fetishist so I'd probably go for the last.

Oli
  • 293,335