1

My main objective is to copy the contents of a directory and send it to a file. Then cut out the directory location to just have the name. Then to organize it's contents but most appeared. This is also homework and my restrictions are it has to be one command

This is what I thought would do the job but it doesn't

wc -l ~location/folder/folder/*.log > ~/log.info | cut -d "/" -f9 ~/log.info | sort

My output

1 /s/s/s/s/location/folder/folder/a.log
1 /s/s/s/s/location/folder/folder/b.log
1 /s/s/s/s/location/folder/folder/c.log
3 /s/s/s/s/location/folder/folder/d.log
2 /s/s/s/s/location/folder/folder/e.log

What I want it to be

1 a
1 b
1 c
2 e
3 d
0

You can strip out all of the bits you don't want by piping the output through sed:

wc -l ~location/folder/folder/*.log > ~/log.info
cut -d "/" -f9 ~/log.info | sort | sed 's_/.*/__;s_\.log$__'
  • Doesn't this also remove the frequency of when they should up? – Joe Feb 4 '16 at 18:30
  • No, it preserves everything before the first / and after the last /, and then snips .log off of the end. – DopeGhoti Feb 4 '16 at 18:56
0

How about:

perl -e 'print sort map {s/(\d).*(\w)\..*//r} <>' 

(Needs perl 5.14+ - this is probably installed on your system already)

Uses an inlined bit of perl code that:

  • reads <> which is STDIN or files specified on command line.
  • Uses a substitution regex which captures a digit (\d) and a letter just before a . (\w)\.
  • then returns the transformed string. r regex flag.
  • uses map to iterate STDIN.
  • and sort to ... well, sort.
  • and print to print it.

Output:

1 a
1 b
1 c
2 e
3 d

Alternatively:

perl -e '%x=map {open($f,'<',$_); @f=<$f>; $_=>''.@f} @ARGV;print "$x{$_} $_\n" for sort {$x{$a}<=>$x{$b}} keys %x;' ~location/folder/folder/*.log 
0
wc … > ~/log.info | cut ~/log.info | …

The two sides of the pipe are executed in parallel. Unless wc is especially quick to finish and cut is especially slow to start, by the time cut reads ~/log.info, it's likely to be still empty, or even nonexistent. To compound the problem, the redirection on sort is also executed in parallel and also truncates the file.

I don't understand what you're trying to do with this intermediate temporary file. It isn't useful:

wc -l ~location/folder/folder/*.log | cut -d "/" -f9 | sort > ~/log.info

It would be simpler to switch to the target directory:

{ cd ~location/folder/folder && wc -l -- *.log; } | sort > ~/log.info

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.