0

I have these data in a file:

one,1,/home/steven/Transformation/users.txt
two,2,/home/steven/Transformation/users.txt

And I want ouptut like this:

one,1,users.txt
two,2,users.txt

How to handle this using awk

0

3 Answers 3

2
awk -F '[,/]' '{print $1","$2","$NF}'

Or with using OFS

awk -F '[,/]' -v OFS=',' '{print $1, $2, $NF}'
2
  • 1
    Since you're using FS you could also use OFS: awk -F '[,/]' -v OFS=',' '{print $1, $2, $NF}' Commented Mar 7, 2020 at 16:31
  • 1
    awk -F / '{print $1 $NF}' Commented Mar 8, 2020 at 12:14
2

You can also use sed:

sed 's;/.*/;;' file

Or with cut and sed:

cut -d / -f1,5 file | sed 's;/;;'

cut and tr

tr '/' ',' < file | cut -d , -f1,2,7

Output:

one,1,users.txt
two,2,users.txt

For this input:

/one,/1,/home/steven/Transformation/users.txt 
/two,/2,/home/steven/Transformation/users.txt

The command:

sed -E 's;(.*,)/.*/;\1;' file

Output:

/one,/1,users.txt 
/two,/2,users.txt
5
  • and how if i have a "/" on the 1st and 2nd but i don't want to escape them?but only the "/" on the 3rd row? Commented Mar 12, 2020 at 16:07
  • @NickAndoniaina could show post a sample of what you mean? Commented Mar 12, 2020 at 16:14
  • The data in the file: /one,/1,/file /two,/2,/file and the desired output i want: /one,/1,file /two,/2,file The "/" of the 3rd row only is escaped Commented Mar 12, 2020 at 16:17
  • /one,/1,/home/steven/Transformation/users.txt /two,/2,/home/steven/Transformation/users.txt and i want this output: /one,/1,users.txt /two,/2,users.txt Commented Mar 12, 2020 at 16:20
  • @NickAndoniaina I updated the answer with the new input. Commented Mar 12, 2020 at 16:56
0

Method1

awk -F "," 'OFS=","{print $1,$2,substr($NF,29)}'  filename

Method2:

sed "s/\/.*\///g" filename

Method3:

#!/usr/bin/python
import re
k=re.compile(r'/.*/')
p=open('p.txt','r')
for i in p:
    print re.sub(k,"",i).strip()

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.