0

While reading results of a ls instance, I'm trying to display a specific term from a specific line using sed :

Here is what I managed to do until now :

echo $(ls -lAtro | sed -n '3p' | cut -d' ' -f 6 )

This is reading the 6th term of the 3rd line. What I'm trying to do is replace the '3p' by a more simple variable which would permit to do something like this :

linetoread=3
echo $(ls -lAtro | sed -n "$linetoread" | cut -d' ' -f 6 )

The above example doesn't work of course, but you get the idea. What can I do to achieve this ? Thanks in advance.

ALGR
  • 319
  • 1
  • 10
  • 1
    `"$linetoread"` --> `"${linetoread}p"`. – John Bollinger Oct 31 '16 at 15:07
  • 2
    `echo $(command)` is the same as `command`, by the way. And secondly, the [output of `ls` isn't meant for parsing](http://mywiki.wooledge.org/ParsingLs). – Benjamin W. Oct 31 '16 at 15:10
  • Thank you for you answer John. This is what I tried but it displays nothing, so I guess it's incorrect. – ALGR Oct 31 '16 at 15:13
  • Benjamin : I know ls isn't meant for parsing, but I have no choice in this particular case. – ALGR Oct 31 '16 at 15:14
  • `"${linetoread}p"` should work. Did you try that code in a simple test case as you have shown in your Q, or plug into a `while` loop or other shell construct? Use `set -vx` to turn on shell debug/trace so you can see how your env-vars are being interpreted. Good luck. – shellter Oct 31 '16 at 15:36

1 Answers1

0

Try awk instead-

line=3 ; 
ls -lAtro | awk -v var="$line" 'NR==var {print $6}' 

This takes the variable line=3 and feeds it into awk (the awk -v part).

The NR==var ensures that you get the line corresponding to your variable.

Then you can change the print $6 part to match whichever column you want. Note that the default delimiter is a space.

Of course, as pointed out in the comments, you shouldn't be parsing the output of ls.

Chem-man17
  • 1,700
  • 1
  • 12
  • 27