-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbasename-dirname.html
119 lines (102 loc) · 15.9 KB
/
basename-dirname.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!doctypehtml><html class="sidebar-visible no-js light"lang=en><head><meta charset=UTF-8><title>basename and dirname - CLI text processing with GNU Coreutils</title><meta content="text/html; charset=utf-8"http-equiv=Content-Type><meta content="Example based guide for specialized text processing with GNU Coreutils"name=description><meta content=width=device-width,initial-scale=1 name=viewport><meta content=#ffffff name=theme-color><meta content="CLI text processing with GNU Coreutils"property=og:title><meta content=website property=og:type><meta content="Example based guide for specialized text processing with GNU Coreutils"property=og:description><meta content=https://learnbyexample.github.io/cli_text_processing_coreutils/ property=og:url><meta content=https://raw.githubusercontent.com/learnbyexample/cli_text_processing_coreutils/main/images/cli_coreutils_ls.png property=og:image><meta content=1280 property=og:image:width><meta content=720 property=og:image:height><meta content=summary_large_image property=twitter:card><meta content=@learn_byexample property=twitter:site><link href=favicon.svg rel=icon><link rel="shortcut icon"href=favicon.png><link href=css/variables.css rel=stylesheet><link href=css/general.css rel=stylesheet><link href=css/chrome.css rel=stylesheet><link href=FontAwesome/css/font-awesome.css rel=stylesheet><link href=fonts/fonts.css rel=stylesheet><link href=highlight.css rel=stylesheet><link href=tomorrow-night.css rel=stylesheet><link href=ayu-highlight.css rel=stylesheet><link href=style.css rel=stylesheet><body><script>var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";</script><script>try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }</script><script>var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');</script><script>var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);</script><nav aria-label="Table of contents"class=sidebar id=sidebar><div class=sidebar-scrollbox><ol class=chapter><li class="chapter-item expanded affix"><a href=cover.html>Cover</a><li class="chapter-item expanded affix"><a href=buy.html>Buy PDF/EPUB versions</a><li class="chapter-item expanded affix"><a href=preface.html>Preface</a><li class="chapter-item expanded"><a href=introduction.html><strong aria-hidden=true>1.</strong> Introduction</a><li class="chapter-item expanded"><a href=cat-tac.html><strong aria-hidden=true>2.</strong> cat and tac</a><li class="chapter-item expanded"><a href=head-tail.html><strong aria-hidden=true>3.</strong> head and tail</a><li class="chapter-item expanded"><a href=tr.html><strong aria-hidden=true>4.</strong> tr</a><li class="chapter-item expanded"><a href=cut.html><strong aria-hidden=true>5.</strong> cut</a><li class="chapter-item expanded"><a href=seq.html><strong aria-hidden=true>6.</strong> seq</a><li class="chapter-item expanded"><a href=shuf.html><strong aria-hidden=true>7.</strong> shuf</a><li class="chapter-item expanded"><a href=paste.html><strong aria-hidden=true>8.</strong> paste</a><li class="chapter-item expanded"><a href=pr.html><strong aria-hidden=true>9.</strong> pr</a><li class="chapter-item expanded"><a href=fold-fmt.html><strong aria-hidden=true>10.</strong> fold and fmt</a><li class="chapter-item expanded"><a href=sort.html><strong aria-hidden=true>11.</strong> sort</a><li class="chapter-item expanded"><a href=uniq.html><strong aria-hidden=true>12.</strong> uniq</a><li class="chapter-item expanded"><a href=comm.html><strong aria-hidden=true>13.</strong> comm</a><li class="chapter-item expanded"><a href=join.html><strong aria-hidden=true>14.</strong> join</a><li class="chapter-item expanded"><a href=nl.html><strong aria-hidden=true>15.</strong> nl</a><li class="chapter-item expanded"><a href=wc.html><strong aria-hidden=true>16.</strong> wc</a><li class="chapter-item expanded"><a href=split.html><strong aria-hidden=true>17.</strong> split</a><li class="chapter-item expanded"><a href=csplit.html><strong aria-hidden=true>18.</strong> csplit</a><li class="chapter-item expanded"><a href=expand-unexpand.html><strong aria-hidden=true>19.</strong> expand and unexpand</a><li class="chapter-item expanded"><a class=active href=basename-dirname.html><strong aria-hidden=true>20.</strong> basename and dirname</a><li class="chapter-item expanded affix"><a href=what_next.html>What next?</a><li class="chapter-item expanded affix"><a href=Exercise_solutions.html>Exercise solutions</a></li><br><hr><li class="chapter-item expanded"><i class="fa fa-github"id=git-repository-button></i><a href=https://github.com/learnbyexample/cli_text_processing_coreutils> Source code</a><li class="chapter-item expanded"><i class="fa fa-home"id=home-button></i><a href=https://learnbyexample.github.io/> My Blog</a><li class="chapter-item expanded"><i class="fa fa-book"id=book-button></i><a href=https://learnbyexample.github.io/books/> My Books</a><li class="chapter-item expanded"><i class="fa fa-envelope"id=mail-button></i><a href=https://learnbyexample.gumroad.com/l/learnbyexample-weekly> learnbyexample weekly</a><li class="chapter-item expanded"><i class="fa fa-twitter"id=twitter-button></i><a href=https://twitter.com/learn_byexample> Twitter</a></ol></div><div class=sidebar-resize-handle id=sidebar-resize-handle></div></nav><div class=page-wrapper id=page-wrapper><div class=page><div id=menu-bar-hover-placeholder></div><div class="menu-bar sticky bordered"id=menu-bar><div class=left-buttons><button aria-label="Toggle Table of Contents"title="Toggle Table of Contents"aria-controls=sidebar class=icon-button id=sidebar-toggle type=button><i class="fa fa-bars"></i></button><button aria-label="Change theme"title="Change theme"aria-controls=theme-list aria-expanded=false aria-haspopup=true class=icon-button id=theme-toggle type=button><i class="fa fa-paint-brush"></i></button><ul aria-label=Themes class=theme-popup id=theme-list role=menu><li role=none><button class=theme id=light role=menuitem>Light (default)</button><li role=none><button class=theme id=rust role=menuitem>Rust</button><li role=none><button class=theme id=coal role=menuitem>Coal</button><li role=none><button class=theme id=navy role=menuitem>Navy</button><li role=none><button class=theme id=ayu role=menuitem>Ayu</button></ul><button aria-label="Toggle Searchbar"title="Search. (Shortkey: s)"aria-controls=searchbar aria-expanded=false aria-keyshortcuts=S class=icon-button id=search-toggle type=button><i class="fa fa-search"></i></button></div><h1 class=menu-title>CLI text processing with GNU Coreutils</h1><div class=right-buttons><a aria-label=Blog href=https://learnbyexample.github.io title=Blog> <i class="fa fa-home"id=home-button></i> </a><a aria-label=Twitter href=https://twitter.com/learn_byexample title=Twitter> <i class="fa fa-twitter"id=twitter-button></i> </a><a aria-label="Git repository"title="Git repository"href=https://github.com/learnbyexample/cli_text_processing_coreutils> <i class="fa fa-github"id=git-repository-button></i> </a></div></div><div class=hidden id=search-wrapper><form class=searchbar-outer id=searchbar-outer><input placeholder="Search this book ..."aria-controls=searchresults-outer aria-describedby=searchresults-header id=searchbar name=searchbar type=search></form><div class="searchresults-outer hidden"id=searchresults-outer><div class=searchresults-header id=searchresults-header></div><ul id=searchresults></ul></div></div><script>document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});</script><div class=content id=content><main><div class=sidetoc><nav class=pagetoc></nav></div><h1 id=basename-and-dirname><a class=header href=#basename-and-dirname>basename and dirname</a></h1><p>These handy commands allow you to extract filenames and directory portions of the given paths. You could also use <a href=https://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion>Parameter Expansion</a> or <code>cut</code>, <code>sed</code>, <code>awk</code>, etc for such purposes. The advantage is that these commands will also handle corner cases like trailing slashes and there are handy features like removing file extensions.<h2 id=extract-filename-from-paths><a class=header href=#extract-filename-from-paths>Extract filename from paths</a></h2><p>By default, the <code>basename</code> command will remove the leading directory component from the given path argument. Any trailing slashes will be removed before determining the portion to be extracted.<pre><code class=language-bash>$ basename /home/learnbyexample/example_files/scores.csv
scores.csv
# quote the arguments when needed
$ basename 'path with spaces/report.log'
report.log
# one or more trailing slashes will not affect the output
$ basename /home/learnbyexample/example_files/
example_files
</code></pre><p>If there's no leading directory component or if slash alone is the input, the argument will be returned as is after removing any trailing slashes.<pre><code class=language-bash>$ basename filename.txt
filename.txt
$ basename /
/
</code></pre><h2 id=remove-file-extension><a class=header href=#remove-file-extension>Remove file extension</a></h2><p>You can use the <code>-s</code> option to remove a suffix from the filename. Usually used to remove the file extension.<pre><code class=language-bash>$ basename -s'.csv' /home/learnbyexample/example_files/scores.csv
scores
$ basename -s'_2' final_report.txt_2
final_report.txt
$ basename -s'.tar.gz' /backups/jan_2021.tar.gz
jan_2021
$ basename -s'.txt' purchases.txt.txt
purchases.txt
# -s will be ignored if it would have resulted in an empty output
$ basename -s'report' /backups/report
report
</code></pre><p>You can also pass the suffix to be removed after the path argument, but the <code>-s</code> option is preferred as it makes the intention clearer and works for multiple path arguments.<pre><code class=language-bash>$ basename example_files/scores.csv .csv
scores
</code></pre><h2 id=remove-filename-from-path><a class=header href=#remove-filename-from-path>Remove filename from path</a></h2><p>By default, the <code>dirname</code> command removes the trailing path component (after removing any trailing slashes).<pre><code class=language-bash>$ dirname /home/learnbyexample/example_files/scores.csv
/home/learnbyexample/example_files
# one or more trailing slashes will not affect the output
$ dirname /home/learnbyexample/example_files/
/home/learnbyexample
</code></pre><h2 id=multiple-arguments><a class=header href=#multiple-arguments>Multiple arguments</a></h2><p>The <code>dirname</code> command accepts multiple path arguments by default. The <code>basename</code> command requires <code>-a</code> or <code>-s</code> (which implies <code>-a</code>) to work with multiple arguments.<pre><code class=language-bash>$ basename -a /backups/jan_2021.tar.gz /home/learnbyexample/report.log
jan_2021.tar.gz
report.log
# -a is implied when the -s option is used
$ basename -s'.txt' logs/purchases.txt logs/report.txt
purchases
report
# dirname accepts multiple path arguments by default
$ dirname /home/learnbyexample/example_files/scores.csv ../report/backups/
/home/learnbyexample/example_files
../report
</code></pre><h2 id=combining-basename-and-dirname><a class=header href=#combining-basename-and-dirname>Combining basename and dirname</a></h2><p>You can use shell features like command substitution to combine the effects of the <code>basename</code> and <code>dirname</code> commands.<pre><code class=language-bash># extract the second last path component
$ basename $(dirname /home/learnbyexample/example_files/scores.csv)
example_files
</code></pre><h2 id=nul-separator><a class=header href=#nul-separator>NUL separator</a></h2><p>Use the <code>-z</code> option if you want to use NUL character as the output path separator.<pre><code class=language-bash>
$ basename -zs'.txt' logs/purchases.txt logs/report.txt | cat -v
purchases^@report^@
$ basename -z logs/purchases.txt | cat -v
purchases.txt^@
$ dirname -z example_files/scores.csv ../report/backups/ | cat -v
example_files^@../report^@
</code></pre><h2 id=exercises><a class=header href=#exercises>Exercises</a></h2><p><strong>1)</strong> Is the following command valid? If so, what would be the output?<pre><code class=language-bash>$ basename -s.txt ~///test.txt///
</code></pre><p><strong>2)</strong> Given the file path in the shell variable <code>p</code>, how'd you obtain the outputs shown below?<pre><code class=language-bash>$ p='~/projects/square_tictactoe/python/game.py'
##### add your solution here
~/projects/square_tictactoe
$ p='/backups/jan_2021.tar.gz'
##### add your solution here
/
</code></pre><p><strong>3)</strong> What would be the output of the <code>basename</code> command if the input has no leading directory component or only has the <code>/</code> character?<p><strong>4)</strong> For the paths stored in the shell variable <code>p</code>, how'd you obtain the outputs shown below?<pre><code class=language-bash>$ p='/a/b/ip.txt /c/d/e/f/op.txt'
# expected output 1
##### add your solution here
ip
op
# expected output 2
##### add your solution here
/a/b
/c/d/e/f
</code></pre><p><strong>5)</strong> Given the file path in the shell variable <code>p</code>, how'd you obtain the outputs shown below?<pre><code class=language-bash>$ p='~/projects/python/square_tictactoe/game.py'
##### add your solution here
square_tictactoe
$ p='/backups/aug_2024/ip.tar.gz'
##### add your solution here
aug_2024
</code></pre></main><nav aria-label="Page navigation"class=nav-wrapper><a aria-label="Previous chapter"class="mobile-nav-chapters previous"title="Previous chapter"aria-keyshortcuts=Left href=expand-unexpand.html rel=prev> <i class="fa fa-angle-left"></i> </a><a aria-label="Next chapter"class="mobile-nav-chapters next"title="Next chapter"aria-keyshortcuts=Right href=what_next.html rel=next> <i class="fa fa-angle-right"></i> </a><div style="clear: both"></div></nav></div></div><nav aria-label="Page navigation"class=nav-wide-wrapper><a aria-label="Previous chapter"class="nav-chapters previous"title="Previous chapter"aria-keyshortcuts=Left href=expand-unexpand.html rel=prev> <i class="fa fa-angle-left"></i> </a><a aria-label="Next chapter"class="nav-chapters next"title="Next chapter"aria-keyshortcuts=Right href=what_next.html rel=next> <i class="fa fa-angle-right"></i> </a></nav></div><script>window.playground_copyable = true;</script><script charset=utf-8 src=elasticlunr.min.js></script><script charset=utf-8 src=mark.min.js></script><script charset=utf-8 src=searcher.js></script><script charset=utf-8 src=clipboard.min.js></script><script charset=utf-8 src=highlight.js></script><script charset=utf-8 src=book.js></script><script src=sidebar.js></script>