user3140605
user3140605

Reputation: 73

Shell script: How to split line?

here's my scanerio:

my input file like:

/tmp/abc.txt
/tmp/cde.txt
/tmp/xyz/123.txt

and i'd like to obtain the following output in 2 files:

first file

/tmp/
/tmp/
/tmp/xyz/

second file

abc.txt
cde.txt
123.txt

thanks a lot

Upvotes: 2

Views: 119

Answers (5)

user4401178
user4401178

Reputation:

Here is another oneliner that uses tee:

cat f1.txt | tee >(xargs -n 1 dirname >> f2.txt) >(xargs -n 1 basename >> f3.txt) &>/dev/random

Upvotes: 0

Jotne
Jotne

Reputation: 41456

Here is all in one single awk

awk -F\/ -vOFS=\/ '{print $NF > "file2";$NF="";print > "file1"}' input

cat file1
/tmp/
/tmp/
/tmp/xyz/

cat file2
abc.txt
cde.txt
123.txt

Here we set input and output separator to /
Then print last field $NF to file2
Set the last field to nothing, then print the rest to file1

Upvotes: 4

quantdev
quantdev

Reputation: 23793

The awk solution is probably the best, but here is a pure sed solution :

#n sed script to get base and file paths
h
s/.*\/\(.*.txt\)/\1/
w file1
g
s/\(.*\)\/.*.txt/\1/
w file2

Note how we hold the buffer with h, and how we use the write (w) command to produce the output files. There are many other ways to do it with sed, but I like this one for using multiple different commands. To use it :

> sed -f sed_script testfile

Upvotes: 0

Dan
Dan

Reputation: 137

I realize you already have an answer, but you might be interested in the following two commands:

basename
dirname

If they're available on your system, you'll be able to get what you want just piping through these:

cat input | xargs -l dirname > file1
cat input | xargs -l basename > file2

Enjoy!

Edit: Fixed per quantdev's comment. Good catch!

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Through grep,

grep -o '.*/' file > file1.txt
grep -o '[^/]*$' file > file2.txt
  • .*/ Matches all the characters from the start upto the last / symbol.
  • [^/]*$ Matches any character but not of / zero or more times. $ asserts that we are at the end of a line.

Upvotes: 0

Related Questions